//! JSON处理工具模块
//! 
//! 对应Java中的JsonUtils类，提供JSON序列化、反序列化、转换等功能

use serde::{Deserialize, Serialize};
use serde_json::{self, Value, Map};
use std::collections::HashMap;

/// JSON错误类型
#[derive(Debug, thiserror::Error)]
pub enum JsonError {
    #[error("JSON serialization error: {0}")]
    Serialization(#[from] serde_json::Error),
    #[error("Type conversion error: {0}")]
    TypeConversion(String),
    #[error("Invalid JSON structure: {0}")]
    InvalidStructure(String),
}

pub type JsonResult<T> = Result<T, JsonError>;

/// 将对象序列化为JSON字符串
/// 
/// # Examples
/// ```
/// use librarys::json_utils::to_json;
/// use serde::Serialize;
/// 
/// #[derive(Serialize)]
/// struct Person {
///     name: String,
///     age: u32,
/// }
/// 
/// let person = Person {
///     name: "Alice".to_string(),
///     age: 30,
/// };
/// 
/// let json_str = to_json(&person).unwrap();
/// assert!(json_str.contains("Alice"));
/// assert!(json_str.contains("30"));
/// ```
pub fn to_json<T: Serialize>(obj: &T) -> JsonResult<String> {
    Ok(serde_json::to_string(obj)?)
}

/// 将对象序列化为格式化的JSON字符串
/// 
/// # Examples
/// ```
/// use librarys::json_utils::to_json_pretty;
/// use serde::Serialize;
/// 
/// #[derive(Serialize)]
/// struct Person {
///     name: String,
///     age: u32,
/// }
/// 
/// let person = Person {
///     name: "Alice".to_string(),
///     age: 30,
/// };
/// 
/// let json_str = to_json_pretty(&person).unwrap();
/// assert!(json_str.contains("  ")); // 包含缩进
/// ```
pub fn to_json_pretty<T: Serialize>(obj: &T) -> JsonResult<String> {
    Ok(serde_json::to_string_pretty(obj)?)
}

/// 从JSON字符串反序列化为对象
/// 
/// # Examples
/// ```
/// use librarys::json_utils::from_json;
/// use serde::Deserialize;
/// 
/// #[derive(Deserialize, PartialEq, Debug)]
/// struct Person {
///     name: String,
///     age: u32,
/// }
/// 
/// let json_str = r#"{"name":"Alice","age":30}"#;
/// let person: Person = from_json(json_str).unwrap();
/// assert_eq!(person.name, "Alice");
/// assert_eq!(person.age, 30);
/// ```
pub fn from_json<T: for<'de> Deserialize<'de>>(json_str: &str) -> JsonResult<T> {
    Ok(serde_json::from_str(json_str)?)
}

/// 解析JSON字符串为Value
/// 
/// # Examples
/// ```
/// use librarys::json_utils::parse_json;
/// 
/// let json_str = r#"{"name":"Alice","age":30}"#;
/// let value = parse_json(json_str).unwrap();
/// assert_eq!(value["name"], "Alice");
/// assert_eq!(value["age"], 30);
/// ```
pub fn parse_json(json_str: &str) -> JsonResult<Value> {
    Ok(serde_json::from_str(json_str)?)
}

/// HashMap转换为JSON Value
/// 
/// # Examples
/// ```
/// use librarys::json_utils::map_to_json;
/// use std::collections::HashMap;
/// 
/// let mut map = HashMap::new();
/// map.insert("name".to_string(), "Alice".to_string());
/// map.insert("city".to_string(), "Beijing".to_string());
/// 
/// let json_value = map_to_json(&map).unwrap();
/// assert_eq!(json_value["name"], "Alice");
/// assert_eq!(json_value["city"], "Beijing");
/// ```
pub fn map_to_json(map: &HashMap<String, String>) -> JsonResult<Value> {
    let mut json_map = Map::new();
    for (key, value) in map {
        json_map.insert(key.clone(), Value::String(value.clone()));
    }
    Ok(Value::Object(json_map))
}

/// Vec转换为JSON数组
/// 
/// # Examples
/// ```
/// use librarys::json_utils::vec_to_json;
/// 
/// let vec = vec!["apple", "banana", "cherry"];
/// let json_array = vec_to_json(&vec).unwrap();
/// assert_eq!(json_array.as_array().unwrap().len(), 3);
/// assert_eq!(json_array[0], "apple");
/// ```
pub fn vec_to_json<T: Serialize>(vec: &[T]) -> JsonResult<Value> {
    Ok(serde_json::to_value(vec)?)
}

/// 通用对象转换为JSON Value
/// 
/// # Examples
/// ```
/// use librarys::json_utils::object_to_json;
/// use serde::Serialize;
/// 
/// #[derive(Serialize)]
/// struct Person {
///     name: String,
///     age: u32,
/// }
/// 
/// let person = Person {
///     name: "Alice".to_string(),
///     age: 30,
/// };
/// 
/// let json_value = object_to_json(&person).unwrap();
/// assert_eq!(json_value["name"], "Alice");
/// assert_eq!(json_value["age"], 30);
/// ```
pub fn object_to_json<T: Serialize>(obj: &T) -> JsonResult<Value> {
    Ok(serde_json::to_value(obj)?)
}

/// 从JSON Value获取字符串值
/// 
/// # Examples
/// ```
/// use librarys::json_utils::{parse_json, get_string};
/// 
/// let json_str = r#"{"name":"Alice","age":30}"#;
/// let value = parse_json(json_str).unwrap();
/// assert_eq!(get_string(&value, "name").unwrap(), "Alice");
/// assert!(get_string(&value, "nonexistent").is_none());
/// ```
pub fn get_string(value: &Value, key: &str) -> Option<String> {
    value.get(key)?.as_str().map(|s| s.to_string())
}

/// 从JSON Value获取整数值
/// 
/// # Examples
/// ```
/// use librarys::json_utils::{parse_json, get_i64};
/// 
/// let json_str = r#"{"name":"Alice","age":30}"#;
/// let value = parse_json(json_str).unwrap();
/// assert_eq!(get_i64(&value, "age").unwrap(), 30);
/// assert!(get_i64(&value, "nonexistent").is_none());
/// ```
pub fn get_i64(value: &Value, key: &str) -> Option<i64> {
    value.get(key)?.as_i64()
}

/// 从JSON Value获取浮点数值
/// 
/// # Examples
/// ```
/// use librarys::json_utils::{parse_json, get_f64};
/// 
/// let json_str = r#"{"score":95.5,"count":10}"#;
/// let value = parse_json(json_str).unwrap();
/// assert_eq!(get_f64(&value, "score").unwrap(), 95.5);
/// assert!(get_f64(&value, "nonexistent").is_none());
/// ```
pub fn get_f64(value: &Value, key: &str) -> Option<f64> {
    value.get(key)?.as_f64()
}

/// 从JSON Value获取布尔值
/// 
/// # Examples
/// ```
/// use librarys::json_utils::{parse_json, get_bool};
/// 
/// let json_str = r#"{"active":true,"disabled":false}"#;
/// let value = parse_json(json_str).unwrap();
/// assert_eq!(get_bool(&value, "active").unwrap(), true);
/// assert_eq!(get_bool(&value, "disabled").unwrap(), false);
/// ```
pub fn get_bool(value: &Value, key: &str) -> Option<bool> {
    value.get(key)?.as_bool()
}

/// 从JSON Value获取数组
/// 
/// # Examples
/// ```
/// use librarys::json_utils::{parse_json, get_array};
/// 
/// let json_str = r#"{"items":["a","b","c"],"count":3}"#;
/// let value = parse_json(json_str).unwrap();
/// let array = get_array(&value, "items").unwrap();
/// assert_eq!(array.len(), 3);
/// assert_eq!(array[0], "a");
/// ```
pub fn get_array<'a>(value: &'a Value, key: &str) -> Option<&'a Vec<Value>> {
    value.get(key)?.as_array()
}

/// 从JSON Value获取对象
/// 
/// # Examples
/// ```
/// use librarys::json_utils::{parse_json, get_object};
/// 
/// let json_str = r#"{"user":{"name":"Alice","age":30}}"#;
/// let value = parse_json(json_str).unwrap();
/// let user_obj = get_object(&value, "user").unwrap();
/// assert_eq!(user_obj["name"], "Alice");
/// ```
pub fn get_object<'a>(value: &'a Value, key: &str) -> Option<&'a Map<String, Value>> {
    value.get(key)?.as_object()
}

/// 检查JSON Value中是否存在指定键
/// 
/// # Examples
/// ```
/// use librarys::json_utils::{parse_json, has_key};
/// 
/// let json_str = r#"{"name":"Alice","age":30}"#;
/// let value = parse_json(json_str).unwrap();
/// assert!(has_key(&value, "name"));
/// assert!(!has_key(&value, "email"));
/// ```
pub fn has_key(value: &Value, key: &str) -> bool {
    value.get(key).is_some()
}

/// 合并两个JSON对象
/// 
/// # Examples
/// ```
/// use librarys::json_utils::{parse_json, merge_json_objects};
/// 
/// let json1 = r#"{"name":"Alice","age":30}"#;
/// let json2 = r#"{"city":"Beijing","age":31}"#;
/// let value1 = parse_json(json1).unwrap();
/// let value2 = parse_json(json2).unwrap();
/// 
/// let merged = merge_json_objects(&value1, &value2).unwrap();
/// assert_eq!(merged["name"], "Alice");
/// assert_eq!(merged["age"], 31); // value2 的值覆盖 value1
/// assert_eq!(merged["city"], "Beijing");
/// ```
pub fn merge_json_objects(obj1: &Value, obj2: &Value) -> JsonResult<Value> {
    let map1 = obj1.as_object().ok_or_else(|| 
        JsonError::InvalidStructure("First parameter is not a JSON object".to_string()))?;
    let map2 = obj2.as_object().ok_or_else(|| 
        JsonError::InvalidStructure("Second parameter is not a JSON object".to_string()))?;
    
    let mut result = map1.clone();
    for (key, value) in map2 {
        result.insert(key.clone(), value.clone());
    }
    
    Ok(Value::Object(result))
}

/// 删除JSON对象中的指定键
/// 
/// # Examples
/// ```
/// use librarys::json_utils::{parse_json, remove_key, has_key};
/// 
/// let json_str = r#"{"name":"Alice","age":30,"city":"Beijing"}"#;
/// let mut value = parse_json(json_str).unwrap();
/// 
/// let removed = remove_key(&mut value, "age").unwrap();
/// assert_eq!(removed, Some(serde_json::Value::Number(serde_json::Number::from(30))));
/// assert!(!has_key(&value, "age"));
/// ```
pub fn remove_key(value: &mut Value, key: &str) -> JsonResult<Option<Value>> {
    match value.as_object_mut() {
        Some(map) => Ok(map.remove(key)),
        None => Err(JsonError::InvalidStructure("Value is not a JSON object".to_string())),
    }
}

/// 设置JSON对象中的键值
/// 
/// # Examples
/// ```
/// use librarys::json_utils::{parse_json, set_value};
/// use serde_json::Value;
/// 
/// let json_str = r#"{"name":"Alice","age":30}"#;
/// let mut value = parse_json(json_str).unwrap();
/// 
/// set_value(&mut value, "city", Value::String("Beijing".to_string())).unwrap();
/// assert_eq!(value["city"], "Beijing");
/// ```
pub fn set_value(value: &mut Value, key: &str, new_value: Value) -> JsonResult<()> {
    match value.as_object_mut() {
        Some(map) => {
            map.insert(key.to_string(), new_value);
            Ok(())
        },
        None => Err(JsonError::InvalidStructure("Value is not a JSON object".to_string())),
    }
}

/// 获取JSON对象的所有键
/// 
/// # Examples
/// ```
/// use librarys::json_utils::{parse_json, get_keys};
/// 
/// let json_str = r#"{"name":"Alice","age":30,"city":"Beijing"}"#;
/// let value = parse_json(json_str).unwrap();
/// let keys = get_keys(&value).unwrap();
/// assert_eq!(keys.len(), 3);
/// assert!(keys.contains(&"name".to_string()));
/// ```
pub fn get_keys(value: &Value) -> JsonResult<Vec<String>> {
    match value.as_object() {
        Some(map) => Ok(map.keys().cloned().collect()),
        None => Err(JsonError::InvalidStructure("Value is not a JSON object".to_string())),
    }
}

/// 验证JSON字符串格式
/// 
/// # Examples
/// ```
/// use librarys::json_utils::is_valid_json;
/// 
/// assert!(is_valid_json(r#"{"name":"Alice","age":30}"#));
/// assert!(!is_valid_json(r#"{"name":"Alice","age":30"#)); // 缺少闭合括号
/// assert!(is_valid_json(r#"[1,2,3]"#));
/// ```
pub fn is_valid_json(json_str: &str) -> bool {
    serde_json::from_str::<Value>(json_str).is_ok()
}

/// 压缩JSON字符串（移除空白字符）
/// 
/// # Examples
/// ```
/// use librarys::json_utils::minify_json;
/// 
/// let pretty_json = r#"{
///   "name": "Alice",
///   "age": 30
/// }"#;
/// let minified = minify_json(pretty_json).unwrap();
/// // Note: JSON object key order may vary
/// assert!(minified.contains("Alice"));
/// assert!(minified.contains("30"));
/// ```
pub fn minify_json(json_str: &str) -> JsonResult<String> {
    let value: Value = serde_json::from_str(json_str)?;
    Ok(serde_json::to_string(&value)?)
}

/// 格式化JSON字符串
/// 
/// # Examples
/// ```
/// use librarys::json_utils::prettify_json;
/// 
/// let compact_json = r#"{"name":"Alice","age":30}"#;
/// let pretty = prettify_json(compact_json).unwrap();
/// assert!(pretty.contains("  ")); // 包含缩进
/// assert!(pretty.contains("\n"));  // 包含换行
/// ```
pub fn prettify_json(json_str: &str) -> JsonResult<String> {
    let value: Value = serde_json::from_str(json_str)?;
    Ok(serde_json::to_string_pretty(&value)?)
}

/// 将字符串数组转换为JSON数组
/// 
/// # Examples
/// ```
/// use librarys::json_utils::string_array_to_json;
/// 
/// let array = vec!["apple".to_string(), "banana".to_string(), "cherry".to_string()];
/// let json_str = string_array_to_json(&array).unwrap();
/// assert!(json_str.contains("apple"));
/// assert!(json_str.contains("banana"));
/// ```
pub fn string_array_to_json(array: &[String]) -> JsonResult<String> {
    Ok(serde_json::to_string(array)?)
}

/// 从JSON数组字符串解析为字符串Vector
/// 
/// # Examples
/// ```
/// use librarys::json_utils::json_to_string_array;
/// 
/// let json_str = r#"["apple","banana","cherry"]"#;
/// let array = json_to_string_array(json_str).unwrap();
/// assert_eq!(array.len(), 3);
/// assert_eq!(array[0], "apple");
/// ```
pub fn json_to_string_array(json_str: &str) -> JsonResult<Vec<String>> {
    Ok(serde_json::from_str(json_str)?)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};

    #[derive(Serialize, Deserialize, Debug, PartialEq)]
    struct TestPerson {
        name: String,
        age: u32,
        active: bool,
    }

    #[test]
    fn test_serialization() {
        let person = TestPerson {
            name: "Alice".to_string(),
            age: 30,
            active: true,
        };

        let json_str = to_json(&person).unwrap();
        assert!(json_str.contains("Alice"));
        assert!(json_str.contains("30"));
        assert!(json_str.contains("true"));

        let pretty_json = to_json_pretty(&person).unwrap();
        assert!(pretty_json.contains("  ")); // 包含缩进
    }

    #[test]
    fn test_deserialization() {
        let json_str = r#"{"name":"Bob","age":25,"active":false}"#;
        let person: TestPerson = from_json(json_str).unwrap();
        
        assert_eq!(person.name, "Bob");
        assert_eq!(person.age, 25);
        assert_eq!(person.active, false);
    }

    #[test]
    fn test_value_operations() {
        let json_str = r#"{"name":"Alice","age":30,"score":95.5,"active":true}"#;
        let value = parse_json(json_str).unwrap();

        assert_eq!(get_string(&value, "name").unwrap(), "Alice");
        assert_eq!(get_i64(&value, "age").unwrap(), 30);
        assert_eq!(get_f64(&value, "score").unwrap(), 95.5);
        assert_eq!(get_bool(&value, "active").unwrap(), true);
        assert!(has_key(&value, "name"));
        assert!(!has_key(&value, "email"));
    }

    #[test]
    fn test_map_and_array_conversion() {
        let mut map = HashMap::new();
        map.insert("city".to_string(), "Beijing".to_string());
        map.insert("country".to_string(), "China".to_string());

        let json_value = map_to_json(&map).unwrap();
        assert_eq!(json_value["city"], "Beijing");

        let vec = vec!["apple", "banana", "cherry"];
        let json_array = vec_to_json(&vec).unwrap();
        assert_eq!(json_array.as_array().unwrap().len(), 3);
    }

    #[test]
    fn test_merge_and_modify() {
        let json1 = r#"{"name":"Alice","age":30}"#;
        let json2 = r#"{"city":"Beijing","age":31}"#;
        let value1 = parse_json(json1).unwrap();
        let value2 = parse_json(json2).unwrap();

        let merged = merge_json_objects(&value1, &value2).unwrap();
        assert_eq!(merged["name"], "Alice");
        assert_eq!(merged["age"], 31); // 被覆盖
        assert_eq!(merged["city"], "Beijing");

        let mut test_value = parse_json(json1).unwrap();
        set_value(&mut test_value, "email", Value::String("alice@example.com".to_string())).unwrap();
        assert_eq!(test_value["email"], "alice@example.com");
    }

    #[test]
    fn test_validation_and_formatting() {
        assert!(is_valid_json(r#"{"name":"Alice"}"#));
        assert!(!is_valid_json(r#"{"name":"Alice""#)); // 无效JSON

        let compact = r#"{"name":"Alice","age":30}"#;
        let pretty = prettify_json(compact).unwrap();
        assert!(pretty.contains("\n"));

        let minified = minify_json(&pretty).unwrap();
        assert!(!minified.contains("\n"));
    }

    #[test]
    fn test_array_conversion() {
        let string_array = vec!["apple".to_string(), "banana".to_string()];
        let json_str = string_array_to_json(&string_array).unwrap();
        
        let parsed_array = json_to_string_array(&json_str).unwrap();
        assert_eq!(parsed_array, string_array);
    }
}